package com.hk.core.autoconfigure.data.r2dbc;

import com.hk.core.data.r2dbc.tenants.ReactiveTenantIdResolver;

import java.util.List;

/**
 * @author Kevin
 * @date 2023-11-12 17:35
 * @see com.hk.core.data.r2dbc.interceptor.R2dbcMultiDatasourceAdvice
 */
//@Aspect
//@Order(value = Integer.MIN_VALUE)
record R2dbcDataSourceAspect(List<ReactiveTenantIdResolver> resolvers) {

//    @Pointcut(value = "execution(* com.hk..repository.r2dbc..*.*(..))")
//    public void pointcut() {
//
//    }
//
//    @Around("pointcut()")
//    public Publisher<?> around(ProceedingJoinPoint joinPoint) throws Throwable {
//        Object target = joinPoint.getTarget();
//        String dbName = null;
//        String methodName = null;
//        DataSourceType dataSourceType;
//        if (joinPoint.getSignature() instanceof MethodSignature signature &&
//                Objects.nonNull(dataSourceType = signature.getMethod().getAnnotation(DataSourceType.class))) {
//            dbName = dataSourceType.value();
//            methodName = signature.getMethod().getName();
//        } else {
//            dataSourceType = AnnotationUtils.findAnnotation(target.getClass(), DataSourceType.class);
//            if (Objects.nonNull(dataSourceType)) {
//                dbName = dataSourceType.value();
//            }
//        }
//        System.out.println(Thread.currentThread().getName() + ",value======methodName=" + methodName + "===" + dbName);
//        return DynamicRoutingConnectionFactory.putR2dbcDataSource((Publisher<?>) joinPoint.proceed(), dbName);
////        return DynamicRoutingConnectionFactory.putR2dbcDataSource((Publisher<?>) joinPoint.proceed(),
////                StringUtils.hasLength(dbName) ? resolve(dbName) : Mono.empty());
//    }
//
////    private Mono<String> resolve(String value) {
////        if (Objects.nonNull(resolvers)) {
////            return Flux.fromIterable(resolvers)
////                    .flatMap(resolver -> resolver.resolve(value))
////                    .filter(StringUtils::hasLength)
////                    .next();
////        }
////        return Mono.empty();
////    }
//
//    private String resolve(String value) {
//        if (Objects.nonNull(resolvers)) {
//            for (ReactiveTenantIdResolver resolver : resolvers) {
//                String val = resolver.resolve(value);
//                if (Objects.nonNull(val)) {
//                    return val;
//                }
//
//            }
//        }
//        return null;
//    }
}
